package com.bobo.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.util.List;
import java.util.Stack;


/**
 * @author Stride.Liu
 */
public class AppManager {
    public Stack<Activity> activityStack;
    private static AppManager instance;

    private AppManager() {
    }

    /**
     * 单例，获取对应应用管理类
     */
    public static AppManager getInstance() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = null;
        try {
            activity = activityStack.lastElement();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 移除指定的Activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (cls == null) {
            return;
        }
        //        if (cls.equals(MyOrderApplyRefundActivity.class)){
        //            finishActivity((Activity)MyOrderApplyRefundActivity);
        //        }
        //        for (Iterator<Activity> activityIterator = activityStack.iterator(); activityIterator.hasNext(); ) {
        //            if (((Activity)activityIterator).getClass().equals(cls)) {
        //                finishActivity((Activity) activityIterator);
        //            }
        //        }
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }

    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        Log.i("AM:activityStack:", activityStack.size() + "");

        if (activityStack == null || activityStack.size() == 0) {
            return;
        }

        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i)
                             .finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 结束当前页面之前的所有Activity
     */
    public void finishCurrentAfterActivity() {
        if (activityStack != null && activityStack.size() > 0) {
            for (int i = 0, size = activityStack.size() - 1; i < size; i++) {
                if (null != activityStack.get(i)) {
                    activityStack.get(i)
                                 .finish();
                }
            }
            activityStack.clear();
        }
    }


    /** 判断程序是否在后台运行 */
//    public static boolean isRunBackground(Context context) {
//        ActivityManager activityManager = (ActivityManager) context
//                .getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
//                .getRunningAppProcesses();
//        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
//            if (appProcess.processName.equals(context.getPackageName())) {
//                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
//                    // 表明程序在后台运行
//                    return true;
//                } else {
//                    return false;
//                }
//            }
//        }
//        return false;
//    }
    /** 判断程序是否在前台运行（当前运行的程序） */
//    public boolean isRunForeground(Context context) {
//        ActivityManager activityManager = (ActivityManager) context.getApplicationContext()
//                .getSystemService(Context.ACTIVITY_SERVICE);
//        String packageName = context.getApplicationContext().getPackageName();
//        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
//                .getRunningAppProcesses();
//        if (appProcesses == null)
//            return false;
//        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
//            if (appProcess.processName.equals(packageName)
//                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//                return true;// 程序运行在前台
//            }
//        }
//        return false;
//    }


    /**
     * 退出应用程序
     *
     * @param context      上下文
     * @param isBackground 是否开开启后台运行
     */
    public void AppExit(Context context, Boolean isBackground) {
        try {
            if (isBackground) {
                PackageManager pm = context.getPackageManager();
                ResolveInfo homeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);

                ActivityInfo ai          = homeInfo.activityInfo;
                Intent startIntent = new Intent(Intent.ACTION_MAIN);
                startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
                startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    context.startActivity(startIntent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(context, "null", Toast.LENGTH_SHORT)
                         .show();
                } catch (SecurityException e) {
                    Toast.makeText(context, "null", Toast.LENGTH_SHORT)
                         .show();
                }
            } else {
                finishAllActivity();

                ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                //activityMgr.restartPackage(context.getPackageName());

                activityMgr.killBackgroundProcesses(context.getPackageName());

                // 注意，如果您有后台程序运行，请不要支持此句子
                System.exit(0);
            }

        } catch (Exception e) {

        }
    }


    /**
     * 判断某个activity是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台,返回true，为显示,否则不是
     */
    public static boolean isForeground(Activity context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

}